package com.srwl.mytx.im;

/**
 * Created by dahai2070 on 2018/3/23 0023.
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.srwl.mytx.Constant;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.Helper;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.FileUtils;
import com.srwl.mytx.utils.IMFileTools;
import com.srwl.mytx.utils.IMImageUtils;
import com.srwl.mytx.utils.IMThumbnailUtils;
import com.srwl.mytx.utils.ImageUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class PicSendThread extends Thread {
    private static final String TAG = "PicSendThread";
    private static int widthpixels;
    private static int heightpixels;
    private List<String> picPaths;
    private Context context;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private PicSendThread.MessageSender messageSender;
    private boolean mNeedCompress = true;
    protected boolean mNeedRound = false;
    protected float mRoundPixels = 0.0F;
    protected boolean mIsMyComputerConv = false;


    public PicSendThread setThumnailNeedRound(boolean mNeedRound) {
        this.mNeedRound = mNeedRound;
        return this;
    }

    public PicSendThread setThumnailRoundPixels(float mRoundPixels) {
        this.mRoundPixels = mRoundPixels;
        return this;
    }

    public PicSendThread setNeedCompress(boolean mNeedCompress) {
        this.mNeedCompress = mNeedCompress;
        return this;
    }

    public PicSendThread setIsMyComputerConv(boolean isMyComputerConv) {
        this.mIsMyComputerConv = isMyComputerConv;
        return this;
    }


    public PicSendThread(List<String> picPaths, Context context, PicSendThread.MessageSender messageSender) {
        this.init(picPaths, context, messageSender);
    }

    private void init(List<String> picPaths, Context context, PicSendThread.MessageSender messageSender) {
        this.picPaths = picPaths;
        this.context = context;
        this.messageSender = messageSender;
        if (widthpixels == 0) {
            widthpixels = context.getResources().getDisplayMetrics().widthPixels;
            heightpixels = (int) ((float) context.getResources().getDisplayMetrics().heightPixels - 32.0F * context.getResources().getDisplayMetrics().density);
        }
        float density = context.getResources().getDisplayMetrics().density;

    }

    public void run() {
        if (this.picPaths != null && !this.picPaths.isEmpty()) {
            File dir = new File(Helper.getInstance().getFilePath());
            dir.mkdirs();
            Iterator i$ = this.picPaths.iterator();

            while (true) {
                while (true) {
                    String originPicPath;
                    int fileSize;
                    File picOriginFile;
                    do {
                        do {
                            if (!i$.hasNext()) {
                                return;
                            }

                            originPicPath = (String) i$.next();
                            fileSize = 0;
                        } while (TextUtils.isEmpty(originPicPath));

                        picOriginFile = new File(originPicPath);
                        if (picOriginFile.exists() && picOriginFile.isFile()) {
                            fileSize = (int) picOriginFile.length();
                        } else {
                            Log.e(TAG, "pic:" + originPicPath + " is empty, pls check!");
                        }
                    } while (this.handleGifPic(originPicPath, fileSize));

                    String imageName = IMImageUtils.genImageName();
                    String savePath = Helper.getInstance().getFilePath() + File.separator + imageName;
                    //获取图片方向
                    int ori = IMImageUtils.getOrientation(originPicPath, this.context, (Uri) null);
                    int originalWidth;
                    int originalHeight;
                    Bitmap origin = null;
                    if (mNeedCompress) {
                        //压缩图片 50%
                        origin = IMThumbnailUtils.compressFileAndRotateToBitmapThumb(originPicPath, widthpixels, heightpixels, ori, savePath, true, false);
                        if (origin == null) {
                            Log.e(TAG, "run: 压缩图片后为空");
                            continue;
                        }

                        originalHeight = origin.getHeight();
                        originalWidth = origin.getWidth();
                    } else {
                        //加载原始大图
                        origin = ImageUtils.getBitmap(originPicPath);
                        if (origin == null) {
                            Log.e(TAG, "run: 原始图片为空");
                            continue;
                        }
//                        BitmapFactory.Options options = new BitmapFactory.Options();
//                        options.inJustDecodeBounds = true;
//                        BitmapFactory.decodeFile(originPicPath, options);

                        originalHeight = origin.getHeight();
                        originalWidth = origin.getWidth();

                    }
                    //预览图地址
                    String previewPath = Helper.getInstance().getFilePath() + File.separator + "preview_" + imageName;
                    float scale;
                    String imageType = "JPEG";
                    scale = IMThumbnailUtils.getScale(originalWidth, originalHeight, context);
                    Rect oriRect = new Rect();
                    if (scale != 1) {

                        float scaleHeight = originalHeight * scale;
                        float scaleWidth = originalWidth * scale;
                        Bitmap scaleBitmap = IMThumbnailUtils.scaleBitmap((int) scaleWidth, (int) scaleHeight, false, origin);
                        // Bitmap scaleBitmap = ImageUtils.compressByScale(origin, scaleWidth, scaleHeight);
                        if (scaleBitmap != null) {
                            imageType = getImageType(originPicPath, picOriginFile, imageType);
                            //保存缩放后的图片
                            if (imageType.equals("JPEG")) {
                                boolean save = ImageUtils.save(scaleBitmap, previewPath, CompressFormat.JPEG, 90);
                                if (!save) {
                                    Log.e(TAG, "run: 本地预览图保存失败");
                                    continue;
                                }
                            } else if (imageType.equals("PNG")) {
                                boolean save = ImageUtils.save(scaleBitmap, previewPath, CompressFormat.PNG, 90);
                                if (!save) {
                                    Log.e(TAG, "run: 本地预览图保存失败");
                                    continue;
                                }
                            }
                            oriRect.set(0, 0, scaleBitmap.getWidth(), scaleBitmap.getHeight());

                        } else {
                            Log.e(TAG, "run: 本地预览图是空的，，，，");
                            continue;
                        }

                    } else {
                        previewPath = savePath;
                        oriRect.set(0, 0, origin.getWidth(), origin.getHeight());

                    }


                    //ImageMsgPacker imageMsgPacker = new ImageMsgPacker(context);
                    //  int mMaxHeight = imageMsgPacker.getMaxNeedServerToGiveThumnailHeight();
                    // int mMinWidth = imageMsgPacker.getMinWidth();
                    // int[] resizedDimension = IMThumbnailUtils.getResizedDimensionOfThumbnail(origin.getWidth(), origin.getHeight(), mMinWidth, mMaxHeight);
                    //对图片进行缩放
                    // Bitmap scalebBitmap = IMThumbnailUtils.getCropAndScaledBitmap(origin, resizedDimension[0], resizedDimension[1], resizedDimension[2], resizedDimension[3], false);
                    //int inSampleSize = origin.getHeight() / mMaxHeight;
                    //如果inSampleSize<1,表示需要放大，放大没有意义，那么就用原图当缩略图用

                    //把图片选择器选取的图片，保存到 Helper.getInstance().getFilePath() 里面
                    savePicToSavePath(originPicPath, savePath, origin);
                    sendImageMessage(savePath, fileSize, previewPath, oriRect, imageType);
                }
            }
        }
    }


    private void savePicToSavePath(String originPicPath, String savePath, Bitmap origin) {
        if (origin != null) {
            try {
                this.saveToSavePath(originPicPath, savePath, this.mNeedCompress, origin);
            } catch (IOException var5) {
                var5.printStackTrace();
                Log.e(TAG, var5.getMessage());
            }
        }

    }

    private void sendImageMessage(final String originPicPath, final int fileSize, final String compressedPath, final Rect oriRect, final String imageType) {

        final Message imageMessage = generateImageMessage(originPicPath, compressedPath, oriRect.width(), oriRect.height(), fileSize, imageType);
        if (this.messageSender != null) this.mHandler.post(new Runnable() {
            public void run() {
                PicSendThread.this.messageSender.sendPicMessage(imageMessage);
            }
        });


    }

    private String getImageType(String originPicPath, File picOriginFile, String imageType) {
        if (picOriginFile.isFile() && picOriginFile.exists() && picOriginFile.exists() && picOriginFile.isFile()) {
            Options decodeOptions = new Options();
            decodeOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(originPicPath, decodeOptions);
            if (decodeOptions != null) {
                Log.d(TAG, "send pic mimeType = " + decodeOptions.outMimeType);
            }

            if (decodeOptions != null && !TextUtils.isEmpty(decodeOptions.outMimeType) && (decodeOptions.outMimeType.contains("png") || decodeOptions.outMimeType.contains("PNG"))) {
                imageType = "PNG";
            }
        }

        return imageType;
    }

    private boolean handleGifPic(String originPicPath, final int fileSize) {
        if (originPicPath.endsWith(".gif")) {
            final String originPath = Helper.getInstance().getFilePath() + File.separator + IMImageUtils.genImageName();
            FileUtils.copyFile(new File(originPicPath), new File(originPath));
            final Options options = new Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(originPicPath, options);
            final Message gifMessage = generateGifMessage(originPath, originPath, options.outWidth, options.outHeight, fileSize);
            if (this.messageSender != null) {
                this.mHandler.post(new Runnable() {
                    public void run() {
                        PicSendThread.this.messageSender.sendPicMessage(gifMessage);
                    }
                });
            }

            return true;
        } else {
            return false;
        }
    }

    private void saveToSavePath(String originPath, String savePath, boolean mNeedCompress, Bitmap bm) throws IOException {
        IMFileTools.deleteFile(savePath);
        if (mNeedCompress) {
            IMFileTools.writeBitmap(savePath, bm, 90);
        } else {
            //如果不需要压缩，就复制了一份而已
            FileUtils.copyFileFast(new File(originPath), new File(savePath));
        }

    }

    private Message generateGifMessage(String filePath, String preFilePath, int width, int height, int size) {
        Message message = new Message();
        message.setType(Constant.C2C_MESSAGE);
        message.setSubType(Constant.IM_TYPE_IMAGE);
        // message.setContent(filePath);
        message.setLocalFilePath(filePath);
        message.setFromId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
        message.setSize(size);
        message.setMimeType("gif");
        message.setPreviewUrl(preFilePath);
        message.setWidth(width);
        message.setHeight(height);
        return message;
    }

    private Message generateImageMessage(String filePath, String preFilePath, int width, int height, int size, String mimeType) {
        Message message = new Message();
        message.setType(Constant.C2C_MESSAGE);
        message.setSubType(Constant.IM_TYPE_IMAGE);
        message.setFromId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
        // message.setContent(filePath);//
        message.setLocalFilePath(filePath);
        // message.setContent(preFilePath);
        message.setSize(size);
        message.setMimeType(mimeType);
        message.setPreviewUrl(preFilePath);
        message.setWidth(width);
        message.setHeight(height);
        return message;
    }

    public interface MessageSender {
        void sendPicMessage(Message var1);
    }
}
